package org.crepi22.finecrop;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.Window;
import java.io.IOException;
import java.lang.reflect.Field;

import javax.imageio.ImageIO;

/**
 * Enum OS specifying the operating system.
 */
public enum OS {
    
    /** The Windows operating system. */
    Windows, 
    
    /** The Unix operating system. */
    Unix, 
    
    /** The Apple (OS X) operating system. */
    Apple,
    
    /** Unknown operating system. */
    Unknown;
    
    private static final String IMAGE_ICON_PATH = "images/icon.png";

    /** The Constant HOME_DIR. */
    public static final String HOME_DIR = System.getProperty("user.dir");  //$NON-NLS-1$
    
    /** The Constant BRAND specifying the OS kind. */
    public static final String BRAND = System.getProperty("os.name").toLowerCase(); //$NON-NLS-1$
    
    /** The Constant APP_NAME defining the application. */
    public static final String APP_NAME = Messages.getString("OS.app_name"); //$NON-NLS-1$
    
    /**
     * Gets the os.
     *
     * @return the os
     */
    public static OS getOS() {
        
        if (BRAND.indexOf("win") >= 0) { //$NON-NLS-1$
            return Windows;
        } else if (BRAND.indexOf("mac") >= 0) { //$NON-NLS-1$
            return Apple;
         // Linux and BSD variants
        } else if (BRAND.indexOf("linux") >= 0 || BRAND.indexOf("bsd") >= 0) { //$NON-NLS-1$ //$NON-NLS-2$
            return Unix; 
        // Do not support Solaris, HP UX and other outdated stuff.
        } else {
            return Unknown;
        }        
    }

    /**
     * Sets the icon and the application name
     *
     * @param frame the frame
     * @param appName the application name
     * @throws IOException Signals that an I/O exception has occurred.
     */
    public static void decorate(Window frame, String appName) throws IOException {
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Class<?> xtoolkit = toolkit.getClass();
        if (appName != null && xtoolkit.getName().equals("sun.awt.X11.XToolkit")) { // NOI18N //$NON-NLS-1$
            try {
                final Field awtAppClassName = xtoolkit.getDeclaredField("awtAppClassName"); // NOI18N //$NON-NLS-1$
                awtAppClassName.setAccessible(true);
                awtAppClassName.set(null, OS.APP_NAME);
            } catch (Exception x) {

            }
        };
        Image im = null;
        im = ImageIO.read(OS.class.getResource(IMAGE_ICON_PATH)); //$NON-NLS-1$
        frame.setIconImage(im);
    }

}
